package com.sinodata.bsm.inmp.task.gab;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.jms.JMSException;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.StatefulJob;

import com.sinodata.bsm.common.vo.Event;
import com.sinodata.bsm.common.vo.Res;
import com.sinodata.bsm.inmp.cache.CacheFactory;
import com.sinodata.bsm.inmp.cache.ResCache;
import com.sinodata.bsm.inmp.message.Messenger;
import com.sinodata.bsm.inmp.util.DBConnectionUtil;
import com.sinodata.bsm.inmp.util.FilePersistUtil;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author wangpeng
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2013-8-19 下午3:42:11          wangpeng        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
@SuppressWarnings("deprecation")
public class WenshiduEventCollectJob implements StatefulJob {

    private static final String FILE_NAME = "gab_wenshidu_timestamp";
    private static final Logger logger = Logger.getLogger(WenshiduEventCollectJob.class);
    private final ResCache resCache = (ResCache) CacheFactory.getCache(ResCache.class);
    private static final SimpleDateFormat adf = new SimpleDateFormat("yyyy/M/d H:mm:ss");
    private static final Long EVENT_TYPE_ID = 602100020000001L;
    private static final int LEVEL = 3;
    private static final String[] confirmedEventSuffixArray = { "恢复正常", "解除" };

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        String timestamp = getTimestamp();
        String sql = getSql(timestamp);
        Connection conn = null;
        Statement statement = null;
        ResultSet set = null;
        conn = DBConnectionUtil.getInstance().getGabConnection();
        List<Event> events = new ArrayList<Event>();
        try {
            statement = conn.createStatement();
            set = statement.executeQuery(sql);
            while (set.next()) {
                String equipNo = set.getString(1);
                String dateStr = set.getString(2);
                Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateStr);
                timestamp = adf.format(date);
                String msg = set.getString(3);
                Res res = resCache.getResIdByIId(equipNo);
                if (res != null) {
                    Event event = new Event();
                    events.add(event);
                    event.setLevel(LEVEL);
                    event.setEventTypeId(EVENT_TYPE_ID);
                    event.setMsg(msg);
                    event.setOccurTime(date);
                    event.setCatalog(1);
                    event.setStatus(0);
                    event.setResId(res.getId());
                    event.setObjectId(msg);
                }
            }
            logger.error("events[" + events.size() + "]");
            Messenger.getInstance().sendEvent(events);
            FilePersistUtil.savePersistentData(FILE_NAME, timestamp);
        } catch (SQLException e) {
            logger.error("GabWsdEventJob 查询access数据库失败", e);
        } catch (IOException e) {
            logger.error("将" + timestamp + "写入文件：" + FILE_NAME + "失败", e);
        } catch (JMSException e) {
            logger.error("温湿度集成发送事件失败", e);
        } catch (ParseException e) {
            logger.error("温湿度集成解析时间失败", e);
        } finally {
            if (conn != null) {
                DBConnectionUtil.getInstance().returnConn(conn);
            }
        }
    }

    private String getSql(String timestamp) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("select ");
        buffer.append("equip_no, ");
        buffer.append("time, ");
        buffer.append("event ");
        buffer.append("from ");
        buffer.append("YcYxEvt ");
        buffer.append("where ");
        buffer.append("time > cdate('" + timestamp + "') ");
        for (int i = 0; i < confirmedEventSuffixArray.length; i++) {
            buffer.append("and ");
            buffer.append("event not like '%");
            buffer.append(confirmedEventSuffixArray[i]);
            buffer.append("' ");
        }
        buffer.append("order by time asc ");
        String sql = buffer.toString();
        logger.error("wenshidu>>>sql[" + sql + "]");
        return sql;
    }

    private String getTimestamp() {
        String timestamp;
        try {
            timestamp = (String) FilePersistUtil.getPersistentData(FILE_NAME);
            if (timestamp == null) {
                timestamp = adf.format(new Date());
            }
        } catch (Exception e) {
            logger.error("wenshidu>>> read data file " + FILE_NAME + " occered error", e);
            timestamp = adf.format(new Date());
        }
        return timestamp;
    }
}
